import 'dart:async';

import 'package:flutter/material.dart';

class CounterTextWidgt2 extends StatelessWidget {
  const CounterTextWidgt2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var bloc2 = CounterProvider2.of(context).bloC;
    print("CounterTextWidgt build: $bloc2");
    return Center(
      child: StreamBuilder(
          initialData: 0,
          stream: bloc2.countStream,
          builder: (context, snapshot) {
            return ActionChip(
                label: Text("${snapshot.data}"),
                onPressed: () {
                  bloc2.counter.add(1);
                });
          }),
    );
  }
}

class ActionBarWidget2 extends StatelessWidget {
  const ActionBarWidget2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var bloc = CounterProvider2.of(context).bloC;
    print("ActionBarWidget build: $bloc");
    return FloatingActionButton(
      onPressed: () {
        bloc.counter.add(1);
      },
      child: Icon(Icons.add),
    );
  }
}

class CounterProvider2 extends InheritedWidget {
  final CounterBloC bloC;

  CounterProvider2({
    required this.bloC,
    Key? key,
    required Widget child,
  }) : super(key: key, child: child);

  static CounterProvider2 of(BuildContext context) {
    final CounterProvider2? result =
        context.dependOnInheritedWidgetOfExactType<CounterProvider2>();
    assert(result != null, 'No CounterProvider found in context');
    return result!;
  }

  @override
  bool updateShouldNotify(CounterProvider2 old) {
    return true;
  }
}

class CounterBloC {
  // actionbtn上的数据
  final _counterActionController = StreamController<int>();

  // 用于往上面的控制器上的stream中添加数据
  StreamSink<int> get counter => _counterActionController.sink;

  final _counterController = StreamController<int>();

  // actionclip使用的stream
  Stream<int> get countStream => _counterController.stream;

  int _count = 0;

  CounterBloC() {
    _counterActionController.stream.listen(onData);
  }

  log() {
    print("BloC");
  }

  void onData(int data) {
    _count = data + _count;
    _counterController.add(_count);
  }

  dispose() {
    _counterActionController.close();
    _counterController.close();
  }
}
